<?php

class MarketController extends BaseController{
    
    public function indexAction(){
        $CurrencyModel = new CurrencyModel();
        $TradeModel = new TradeModel();
        $trade_currency = $CurrencyModel->getTradeCurrency();

        $currency = $CurrencyModel->getMarket();
        foreach ($currency as $k => $v) {
            $list=$TradeModel->getCurrencyMessageById($v['currency_id'],$v['trade_currency_id']);
            $currency[$k]=array_merge($list,$currency[$k]);
            $currency[$k]['currency'] = $CurrencyModel->getCurrencynameById($v['currency_id']);
            $trade_currency = $CurrencyModel->getCurrencynameById($v['trade_currency_id']);
            $currency[$k]['trade_currency'] = $trade_currency;
            
            $rs=$CurrencyModel->getCurrencyUser($this->member['member_id'],$v['currency_id']);
            if(!$rs){
                $CurrencyModel->addCurrencyUser($this->member['member_id'],$v['currency_id']);
            }
            $data[$trade_currency['currency_mark']]['list'][] = $currency[$k];
            $data[$trade_currency['currency_mark']]['currency_mark'] = $trade_currency['currency_mark'];
            $data[$trade_currency['currency_mark']]['currency_name'] = $trade_currency['currency_name'];
        }
        $this->assign('currency',$data);
        $this->show('Market/index.php');
    }

    public function tradeAction(){
        $CurrencyModel = new CurrencyModel();
        $currencyMark = $this->input('get','currency');
        $currency = $CurrencyModel->getCurrencyByCurrencyMark($currencyMark,'market_id,currency_id,currency_buy_fee,currency_sell_fee,trade_currency_id');
        $trade_currency = $CurrencyModel->getTradeCurrency();
        $this->assign('trade_currency_market',$trade_currency);
        if($currency){
            $Rsa = new Rsa();
            //检查用户币种信息
            $rs=$CurrencyModel->getCurrencyUser($this->member['member_id'],$currency['currency_id']);
            if(!$rs){
                $CurrencyModel->addCurrencyUser($this->member['member_id'],$currency['currency_id']);
            }
            $signData['currency_id'] = intval($currency['currency_id']);
            $signData['trade_currency_id'] = intval($currency['trade_currency_id']);
            $signData['member_id'] = isset($this->member['member_id'])?intval($this->member['member_id']):0;
            $signData['code'] = md5(Yaf\Registry::get('config')->application->token);
            ksort($signData);
            $token = $Rsa->sign(json_encode($signData));
            $this->assign('token',$token);

            $this->assign('currency',$currency);
            $this->assign('wsslink',Yaf\Registry::get('serverConfig')->ws->url);
            $this->show('Market/trade.php');
        }else{
            $this->error(L('access_denied'));
        }
    }

    public function buyAction(){
        if(IS_POST){
            Yaf\loader::import(APP_PATH.'/common/lib/WebSocketClient.php');
            $Rsa = new Rsa();
            $CurrencyModel = new CurrencyModel();
            $OrdersModel = new OrdersModel();
            $client = new WebSocketClient(Yaf\Registry::get('serverConfig')->ws->ServerIp,Yaf\Registry::get('serverConfig')->ws->port);
            $clientConnect = $client->connect();
            if(!$clientConnect){
                $this->ajaxReturn(array('err'=>'1','msg'=>L('server_err')));
            }

            $market_id = $this->input('post','market_id');
            $price = $this->input('post','price');
            $num = $this->input('post','num');
            $data['type'] = 'buy';
            $data['member_id'] = $this->member['member_id'];
            $data['market_id'] = $market_id;
            $data['price'] = $price;
            $data['num'] = $num;
            //判断用户是否存在
            if (!$data['member_id']){
                $this->ajaxReturn(array('err'=>1,'msg'=>L('_no_login')));
            }
            //获取币的信息
            $currency=$CurrencyModel->getCurrencyByMarketId($data['market_id']);
            if ($currency['is_lock']){
                $this->ajaxReturn(array('err'=>1,'msg'=>L('_currency_not_open')));
            }
            if(!is_numeric($data['price'])||!is_numeric($data['num'])){
                $this->ajaxReturn(array('err'=>1,'msg'=>L('_price_num_is_number')));
            }
            // $buy_one = $OrdersModel->getOneOrdersByPrice($currency['currency_id'],$currency['trade_currency_id'], 'buy');
            //交易价格必须大于1
            if ($data['price']<0){
                $this->ajaxReturn(array('err'=>1,'msg'=>L('_trade_price_gt_zero')));
            }
            // if($data['price']<$buy_one*0.9){
            //     $this->ajaxReturn(array('err'=>1,'msg'=>L('_price_lower')));
            // }
            //数量必须大于0
            if ($data['num']<0.001){
                $this->ajaxReturn(array('err'=>1,'msg'=>L('_number_lower')));
            }
            //涨停价格限制
            if ($currency['price_down']>0&&$data['price']<$currency['price_down']){
                $this->ajaxReturn(array('err'=>1,'msg'=>L('_limit_down')));
            }
            //涨停价格限制
            if ($currency['price_up']>0&&$data['price']>$currency['price_up']){
                $this->ajaxReturn(array('err'=>1,'msg'=>L('_daily_limit')));
            }
            //检查用户金额
            if ($CurrencyModel->checkUserMoney($data['num'], $data['price'], $data['type'],$data['member_id'], $currency)){
                $this->ajaxReturn(array('err'=>1,'msg'=>L('_amount_enough')));
            }
            $data['trade_currency_id'] = intval($currency['trade_currency_id']);
            $signData = $data;
            $signData['code'] = md5(Yaf\Registry::get('config')->application->token);
            ksort($signData);
            //发送数据
            $sendData = array(
                'action'=>'addOrder',
                'data'=>$data,
                'token'=>$Rsa->sign(json_encode($signData))
            );
            $client->send(json_encode($sendData));
            $result = $client->recv();
            if($result>=0){
                MemberModel::log($this->member['member_id'],$data,1);
                $this->ajaxReturn(array('err'=>0,'msg'=>L('_order_success')));
            }else{
                MemberModel::log($this->member['member_id'],$data,0);
                $this->ajaxReturn(array('err'=>1,'msg'=>L('_order_err')));
            }
        }
    }


    public function sellAction(){
        if(IS_POST){
            Yaf\loader::import(APP_PATH.'/common/lib/WebSocketClient.php');
            $Rsa = new Rsa();
            $CurrencyModel = new CurrencyModel();
            $OrdersModel = new OrdersModel();
            $client = new WebSocketClient(Yaf\Registry::get('serverConfig')->ws->ServerIp,Yaf\Registry::get('serverConfig')->ws->port);
            $clientConnect = $client->connect();
            if(!$clientConnect){
                $this->ajaxReturn(array('err'=>'1','msg'=>L('server_err')));
            }

            $market_id = $this->input('post','market_id');
            $price = $this->input('post','price');
            $num = $this->input('post','num');
            $data['type'] = 'sell';
            $data['member_id'] = $this->member['member_id'];
            $data['market_id'] = $market_id;
            $data['price'] = $price;
            $data['num'] = $num;
            //判断用户是否存在
            if (!$data['member_id']){
                $this->ajaxReturn(array('err'=>1,'msg'=>L('_no_login')));
            }
            //获取币的信息
            $currency=$CurrencyModel->getCurrencyByMarketId($data['market_id']);
            if ($currency['is_lock']){
                $this->ajaxReturn(array('err'=>1,'msg'=>L('_currency_not_open')));
            }
            if(!is_numeric($data['price'])||!is_numeric($data['num'])){
                $this->ajaxReturn(array('err'=>1,'msg'=>L('_price_num_is_number')));
            }
            $sell_one = $OrdersModel->getOneOrdersByPrice($currency['currency_id'],$currency['trade_currency_id'], 'sell');
            //交易价格必须大于1
            if ($data['price']<0){
                $this->ajaxReturn(array('err'=>1,'msg'=>L('_trade_price_gt_zero')));
            }
            if($data['price']<$sell_one*0.9){
                $this->ajaxReturn(array('err'=>1,'msg'=>L('_price_lower')));
            }
            //数量必须大于0
            if ($data['num']<0.001){
                $this->ajaxReturn(array('err'=>1,'msg'=>L('_number_lower')));
            }
            //涨停价格限制
            if ($currency['price_down']>0&&$data['price']<$currency['price_down']){
                $this->ajaxReturn(array('err'=>1,'msg'=>L('_limit_down')));
            }
            //涨停价格限制
            if ($currency['price_up']>0&&$data['price']>$currency['price_up']){
                $this->ajaxReturn(array('err'=>1,'msg'=>L('_daily_limit')));
            }
            //检查用户金额
            if ($CurrencyModel->checkUserMoney($data['num'], $data['price'], $data['type'],$data['member_id'], $currency)){
                $this->ajaxReturn(array('err'=>1,'msg'=>L('_amount_enough')));
            }
            $data['trade_currency_id'] = $currency['trade_currency_id'];
            $signData = $data;
            $signData['code'] = md5(Yaf\Registry::get('config')->application->token);
            ksort($signData);
            //发送数据
            $sendData = array(
                'action'=>'addOrder',
                'data'=>$data,
                'token'=>$Rsa->sign(json_encode($signData))
            );
            $client->send(json_encode($sendData));
            $result = $client->recv();
            if($result>=0){
                MemberModel::log($this->member['member_id'],$data,1);
                $this->ajaxReturn(array('err'=>0,'msg'=>L('_order_success')));
            }else{
                MemberModel::log($this->member['member_id'],$data,0);
                $this->ajaxReturn(array('err'=>1,'msg'=>L('_order_err')));
            }
        }
    }


    public function delAction(){
        if(IS_POST){
            Yaf\loader::import(APP_PATH.'/common/lib/WebSocketClient.php');
            $Rsa = new Rsa();
            $OrdersModel = new OrdersModel();
            $client = new WebSocketClient(Yaf\Registry::get('serverConfig')->ws->ServerIp,Yaf\Registry::get('serverConfig')->ws->port);
            $clientConnect = $client->connect();
            if(!$clientConnect){
                $this->ajaxReturn(array('err'=>'1','msg'=>L('server_err')));
            }

            $orders_id = $this->input('get','orders_id');
            $data['member_id'] = $this->member['member_id'];
            $data['orders_id'] = $orders_id;
            //判断用户是否存在
            if (!$data['member_id']){
                $this->ajaxReturn(array('err'=>1,'msg'=>L('_no_login')));
            }
            $order = $OrdersModel->getOneOrdersByMemberAndOrderId($data['member_id'],$data['orders_id'],array(0,1));
            if(!$order){
                $this->ajaxReturn(array('err'=>1,'msg'=>L('_order_num_err')));
            }

            $signData = $data;
            $signData['code'] = md5(Yaf\Registry::get('config')->application->token);
            ksort($signData);
            //发送数据
            $sendData = array(
                'action'=>'delOrder',
                'data'=>$data,
                'token'=>$Rsa->sign(json_encode($signData))
            );
            $client->send(json_encode($sendData));
            $result = $client->recv();
            if($result>=0){
                MemberModel::log($this->member['member_id'],$data,1);
                $this->ajaxReturn(array('err'=>0,'msg'=>L('_cancel_success')));
            }else{
                MemberModel::log($this->member['member_id'],$data,0);
                $this->ajaxReturn(array('err'=>1,'msg'=>L('_cancel_err')));
            }
        }
    }

    // public function get_klineAction(){
    //     $currency_id = $this->input('get','currency_id',0);
    //     $trade_currency_id = $this->input('get','trade_currency_id',0);
    //     // if(!$currency_id || !$trade_currency_id) return false;
    //     $time = $this->input('get','time','kline_1d');
    //     $TradeModel = new TradeModel();
    //     switch ($time){
    //         case 'kline_5m':$time=5;break;
    //         case 'kline_15m':$time=15;break;
    //         case 'kline_30m':$time=30;break;
    //         case 'kline_1h':$time=60;break;
    //         case 'kline_8h':$time=480;break;
    //         case 'kline_1d':$time=24*60;break;
    //         default:$time=60;
    //     }
    //     $result = $TradeModel->getKline($time,$currency_id,$trade_currency_id);
    //     if($result){
    //         $this->ajaxReturn(array('err'=>0,'msg'=>'ok','data'=>$result));
    //     }else{
    //         $this->ajaxReturn(array('err'=>0,'msg'=>'fail','data'=>''));
    //     }
    // }
}